package com.onLineCar.management.utils;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import com.onLineCar.management.domain.request.ContractRequest;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.HashMap;

/**
 * @Project cloud-server
 * @Author 王方俞
 * @Date 2023/12/28 9:57
 * @Description
 */
@Service
public class WordExportService {


    public void exportWord(HttpServletResponse response, ContractRequest contractRequest) throws Exception {
//        byte[] signatureBytes = Base64.getDecoder().decode(driverExportRequest.getSignatureBase64());
//        InputStream inputStream = new ByteArrayInputStream(signatureBytes);
        InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Contract.docx");
        if (null == resourceAsStream) {
            throw new Exception("模板文件不存在");
        }
        XWPFTemplate template = XWPFTemplate.compile(resourceAsStream).render(
                new HashMap<String, Object>() {{
                    // 将合同请求中的姓名存入Map中，如果姓名为空，则存入"/"
                    put("name", null == contractRequest.getName() ? "/" : contractRequest.getName());
                    // 将合同请求中的身份证存入Map中，如果身份证为空，则存入"/"
                    put("sfz", null == contractRequest.getSfz() ? "/" : contractRequest.getSfz());
                    // 将合同请求中的电话存入Map中，如果电话为空，则存入"/"
                    put("phone", null == contractRequest.getPhone() ? "/" : contractRequest.getPhone());
                    // 获取当前日期
                    LocalDate now = LocalDate.now();
                    // 将当前年份存入Map中
                    put("ey", now.getYear());
                    // 将当前月份存入Map中
                    put("em", now.getMonthValue());
                    // 将当前日期存入Map中
                    put("ed", now.getDayOfMonth());
                    // 将当前年份存入Map中
                    put("yy", now.getYear());
                    // 将当前月份存入Map中
                    put("mm", now.getMonthValue());
                    // 将当前日期存入Map中
                    put("dd", now.getDayOfMonth());
//                    put("signature", Pictures.ofStream(inputStream, PictureType.PNG).size(140, 60).create());
                }});
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=\"" + "Contract.docx" + "\"");

        // HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    }
}
